package com.jmda.platform.repository.worklist.service;

import com.jmda.platform.commom.BaseService;
import com.jmda.platform.commom.ResourcePathConfig;
import com.jmda.platform.commom.SequenceService;
import com.jmda.platform.commom.util.FileUtil;
import com.jmda.platform.database.DataBaseService;
import com.jmda.platform.repository.ResositoryException;
import com.jmda.platform.repository.mybatis.service.MybatisXmlMappersService;
import com.jmda.platform.repository.worklist.cache.WorkListCache;
import com.jmda.platform.repository.worklist.model.ButtonModel;
import com.jmda.platform.repository.worklist.model.ColumnModel;
import com.jmda.platform.repository.worklist.model.SearchModel;
import com.jmda.platform.repository.worklist.model.WorkListModel;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class WorkListService implements BaseService<WorkListModel> {
	@Resource
	WorkListCache cache;
	@Resource
	ResourcePathConfig resourceLoaderPath;
	@Resource
	SequenceService seq;
	@Resource
	MybatisXmlMappersService mybatis;
	public List<WorkListModel> getAll() throws ResositoryException {
		// TODO Auto-generated method stub
		return cache.getAll();
	}

	@Override
	public WorkListModel get(String id) throws ResositoryException {
		// TODO Auto-generated method stub
		return cache.get(id);
	}

	public ColumnModel getColumnModel(String id, String columnId) throws ResositoryException {
		WorkListModel workListModel = get(id);
		if (workListModel != null && workListModel.getColumn() != null) {

			for (ColumnModel model : workListModel.getColumn()) {
				if (model.getId().equals(columnId)) {
					return model;
				}
			}
		}
		return null;
	}

	public ColumnModel getColumnModelByName(String id, String columnName) throws ResositoryException {
		WorkListModel workListModel = get(id);
		if (workListModel != null && workListModel.getColumn() != null) {

			for (ColumnModel model : workListModel.getColumn()) {
				if (model.getColumnName().equals(columnName)) {
					return model;
				}
			}
		}
		return null;
	}
	
	public ColumnModel getColumnModelPK(String id) throws ResositoryException {
		WorkListModel workListModel = get(id);
		if (workListModel != null && workListModel.getColumn() != null) {
			for (ColumnModel model : workListModel.getColumn()) {
				if (model.isPk()) {
					return model;
				}
			}
		}
		return null;
	}

	@Override
	public void remove(String id) throws ResositoryException {
		// TODO Auto-generated method stub
		try {
			mybatis.remove(cache.getFilePath(), id);
			FileUtil.removeFile(cache.getFilePath() + id + ".xml");
			FileUtil.removeFile(cache.getFilePath() + id + "_dao.xml");
			Object[] params = {id};
			
			cache.remove(id);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new ResositoryException(e);
		}
	}

	

	@Override
	public String store(WorkListModel model) throws ResositoryException {
		// TODO Auto-generated method stub
		if (model.getId() == null || model.getId().trim().length() == 0) {
			model.setId(seq.getUUID());
		}

		// 指定编码解析器
		XStream xstream = new XStream(new DomDriver("utf-8"));
		// 如果没有这句，xml中的根元素会是<包.类名>；或者说：注解根本就没生效，所以的元素名就是类的属性
		xstream.processAnnotations(WorkListModel.class);
		xstream.aliasSystemAttribute(null, "class");
		String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + xstream.toXML(model);
		try {
			mybatis.storeWorkList(cache.getFilePath(), model.getId(), converSql(model));
			FileUtil.write(cache.getFilePath() + model.getId() + ".xml", xmlString);
			cache.put(model);
		} catch (IOException e) {
			throw new ResositoryException(e);
		}
		/*try {
			Object[] params = {model.getId()};
			List<WorkListDBModel> list = db.queryList("select WORKLIST_ID from mda_worklist where WORKLIST_ID = ?", WorkListDBModel.class, params);
			if(list!=null&&list.size()>0){
				Blob blob = new SerialBlob(xmlString.getBytes());//String 转 blo //Hibernate.createBlob(content.getBytes());  
			    Object[] upParams = {blob,model.getId()};
			    db.update("update mda_worklist set XML_CONTENT = ? where WORKLIST_ID = ?", upParams);
			}else{
				Blob blob = new SerialBlob(xmlString.getBytes());
				Object[] upParams = {model.getId(),model.getName(),blob};
				db.update("insert into mda_worklist(WORKLIST_ID,NAME,XML_CONTENT) values(?,?,?)", upParams);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return model.getId();
	}

	public String create(String name, String applicationId, String xieyin_code) throws ResositoryException {
		// TODO Auto-generated method stub
		WorkListModel model = new WorkListModel();
		model.setId(seq.getUUID());
		model.setName(name);
		model.setXieyin_code(xieyin_code);
		model.setApplicationId(applicationId);
		List<ButtonModel> buttons=new ArrayList<ButtonModel>();
		ButtonModel addBtn=new ButtonModel();
		addBtn.setId(seq.getUUID());
		addBtn.setHandler("addData();");
		addBtn.setIconCls("fa fa-plus");
		addBtn.setTitle("新增");
		addBtn.setTooltip("新增");
		addBtn.setOrderIndex(1);
		
		ButtonModel modifyBtn=new ButtonModel();
		modifyBtn.setId(seq.getUUID());
		modifyBtn.setHandler("updateData();");
		modifyBtn.setIconCls("fa fa-edit");
		modifyBtn.setTitle("修改");
		modifyBtn.setTooltip("修改");
		modifyBtn.setOrderIndex(2);
		
		ButtonModel delBtn=new ButtonModel();
		delBtn.setId(seq.getUUID());
		delBtn.setHandler("deleteDatas();");
		delBtn.setIconCls("fa fa-times");
		delBtn.setTitle("删除");
		delBtn.setTooltip("删除");
		delBtn.setOrderIndex(3);
		buttons.add(addBtn);
		buttons.add(modifyBtn);
		buttons.add(delBtn);
		model.setButton(buttons);
		store(model);
		return model.getId();
	}
	public String create(WorkListModel model) throws ResositoryException {
		// TODO Auto-generated method stub
		store(model);
		return model.getId();
	}

	@Override
	public List<WorkListModel> queryList(WorkListModel param) {
		// TODO Auto-generated method stub
		return cache.queryList(param);
	}

	@Override
	public WorkListModel queryOne(WorkListModel param) {
		// TODO Auto-generated method stub
		return cache.queryList(param).get(0);
	}

	private String converSql(WorkListModel model) {
		String sql = model.getSql()==null?"":model.getSql();
		List<SearchModel> list = model.getSearchWhere();
		StringBuffer param = new StringBuffer();
		param.append("1=1 ");
		if (sql != null && sql.trim().length() > 0 && list != null && list.size() > 0 && sql.indexOf("???") > -1) {
			for (SearchModel searchModel : list) {
				param.append("").append("<if test=\"" + searchModel.getId() + " != null \">");
				if (searchModel.getWhere().equals("like")) {
					param.append("").append(" and ").append(searchModel.getColumnName()).append("  <![CDATA[").append(searchModel.getWhere()).append(" CONCAT('%','${").append(searchModel.getId()).append("}','%')");
				} else {
					param.append("").append(" and ").append(searchModel.getColumnName()).append("  <![CDATA[").append(searchModel.getWhere()).append(" #{").append(searchModel.getId()).append("}");
				}
				param.append("]]>").append("</if>");
			}
		}
		sql = sql.replace("???", param.toString());
		return sql;
	}
	public int getWorkListSearchWhereNextIndex(WorkListModel model) {
		List<SearchModel> list = model.getSearchWhere();
		if (list != null && list.size() > 0) {
			Collections.sort(list, new Comparator<SearchModel>() {
				public int compare(SearchModel arg0, SearchModel arg1) {
					return arg1.getOrderIndex() - arg0.getOrderIndex();
				}
			});
			return list.get(0).getOrderIndex()+1;
		}
		return 0;
	}
	
	public int getWorkListButtonNextIndex(WorkListModel model) {
		List<ButtonModel> list = model.getButton();
		if (list != null && list.size() > 0) {
			Collections.sort(list, new Comparator<ButtonModel>() {
				public int compare(ButtonModel arg0, ButtonModel arg1) {
					return arg1.getOrderIndex() - arg0.getOrderIndex();
				}
			});
			return list.get(0).getOrderIndex()+1;
		}
		return 0;
	}
	
	public int getWorkListColumnNextIndex(WorkListModel model) {
		List<ColumnModel> list = model.getColumn();
		if (list != null && list.size() > 0) {
			Collections.sort(list, new Comparator<ColumnModel>() {
				public int compare(ColumnModel arg0, ColumnModel arg1) {
					return arg1.getOrderIndex() - arg0.getOrderIndex();
				}
			});
			return list.get(0).getOrderIndex()+1;
		}
		return 0;
	}
}

